<?php

namespace addons\sum\listener;

use addons\sum\service\Wallet as WalletService;
use app\admin\model\sum\performer\Follow as PerformerFollowModel;
use app\admin\model\sum\Task as TaskModel;
use app\admin\model\sum\user\User as UserModel;
use app\admin\model\sum\user\WalletLog;
use app\admin\model\sum\video\Log as VideoLogModel;

class Task
{

    // 任务时间
    public function taskEvent($params)
    {
        $event = $params['event'];//事件
        $user = $params['user'];//用户
        if(!$user){
            return false;
        }
        $task=TaskModel::where('status','normal')->where('hook',$event)->find();
        if($task){
            $map_uwl=[];
            $map_uwl['user_id']=$user['id'];
            $map_uwl['type']='score';
            $map_uwl['event']=$task['hook'];//该任务事件产生的金币流水
            if($task['type']=='day'){
                $today_date=strtotime('today');
                $map_uwl['createtime']=['>=',$today_date];
            }
            $user_wallet_log=WalletLog::where($map_uwl)->find();
            $is_finish=$this->checkIsFinish($params);
            if(!$user_wallet_log&&$is_finish){
                //结算积分
                $score=$task['score'];
                if($score>0){
                    WalletService::change($user, 'score', $score, $event);
                }
            }
        }
    }

    // 检测是否已经完成任务
    private function checkIsFinish($params)
    {
        $event = $params['event'];//事件
        $user = $params['user'];//用户
        // 这些是只要进来就算完成的事件
        if(in_array($event,['task_video_share','task_video_comment','task_video_like','task_performer_gift'])){
            return true;
        }
        if($event=='task_performer_rank'){//进榜单前十 //作废
            $performer_id = $params['performer_id'];//演员
            $user_follow=PerformerFollowModel::where('performer_id',$performer_id)->where('user_id',$user['id'])->find();
            if($user_follow){
                $gt_user_count=PerformerFollowModel::where('performer_id',$performer_id)->where('popularity','>',$user_follow['popularity'])->count();
                if($gt_user_count<10){
                    return true;
                }
            }
        }
        if($event=='task_video_watch'){//观看视频 - 三集
            $task=TaskModel::where('status','normal')->where('hook',$event)->find();
            $map_v_log['user_id']=$user['id'];
            $map_v_log['type']=1;
            if($task['type']=='day'){
                $today_date=strtotime('today');
                $map_v_log['createtime']=['>=',$today_date];
            }
            $v_log_count=VideoLogModel::where($map_v_log)->count();
            if($v_log_count>=3){
                return true;
            }
        }
        return false;
    }

}
